import { ref, watchEffect, toValue } from 'vue'

// export function useFetch(url) {
//     const data = ref(null)
//     const error = ref(null)

//     fetch(toValue(url))
//     .then((res) => res.json())
//     .then((json) => data.value = json)
//     .catch((err) => error.value = err)

//     return { data, error }
// }

export function useFetchOnWatch(url) {
    const data = ref(null)
    const error = ref(null)

    watchEffect(async () => {
        data.value = null
        error.value = null
        const urlValue = toValue(url)

        try {
            await mockError()

            const res = await fetch(urlValue)
            data.value = await res.json()
        } catch (e) {
            error.value = e
        }
    })

    return { data, error }
}

function mockError() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (Math.random() > 0.3) {
                resolve()
            } else {
                reject(new Error('Mock Error'))
            }
        }, 300)
    })
}